package kz.kstu.scantest.business.server.context;

import kz.kstu.scantest.business.server.api.Service;

import java.util.HashMap;
import java.util.Map;


/**
 * @author Filipp_Stankevich
 *         created: 01.08.11 19:41
 */
public abstract class AbstractServerContextManager {

    private final static String API_PACKAGE_NAME = "api";
    private final static String IMPL_PACKAGE_NAME = "impl";
    private final static String IMPL_CLASS_POSTFIX = "Impl";
    private final static Map<String, Service> SERVICE_CACHE = new HashMap<String, Service>();

    private ServerContext serverContext;

    protected <T extends Service> T getService(Class<T> serviceInterface) {
        String serviceName = serviceInterface.getSimpleName();
        T service;
        if (SERVICE_CACHE.containsKey(serviceName)) {
            service = (T) SERVICE_CACHE.get(serviceName);
        } else {
            String className = serviceInterface.getName().replace(API_PACKAGE_NAME, IMPL_PACKAGE_NAME) + IMPL_CLASS_POSTFIX;
            try {
                Class<T> serviceClass = (Class<T>) Class.forName(className);
                service = serviceClass.newInstance();
                service.setServerContext(serverContext);
                SERVICE_CACHE.put(serviceName, service);
            } catch (ClassNotFoundException e) {
                throw new IllegalArgumentException("Error during getting service: " + serviceInterface.getSimpleName(), e);
            } catch (InstantiationException e) {
                throw new IllegalArgumentException("Error during getting instance of service: " + serviceInterface.getSimpleName(), e);
            } catch (IllegalAccessException e) {
                throw new IllegalArgumentException("Error during getting instance of service: " + serviceInterface.getSimpleName(), e);
            }
        }
        return service;
    }

    public void setServerContext(ServerContext serverContext) {
        this.serverContext = serverContext;
    }

    protected ServerContext getServerContext() {
        return serverContext;
    }
}
